package com.bwie.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bwie.auth.fegin.AuthFeginService;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.UserRequest;
import com.bwie.common.domain.response.JwtResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthFeginService authFeginService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private HttpServletRequest request;

    @Override
    public Result sendCode(String phone) {
        if(!validPhone(phone)){
            return Result.error("手机号格式不正确");
        }
        User byPhone = authFeginService.findByPhone(phone);
        if(byPhone==null){
            return Result.error("手机号不存在");
        }
        String code = RandomUtil.randomNumbers(4);

        rabbitTemplate.convertAndSend("sendMsg",phone,message -> {
            message.getMessageProperties().setMessageId(UUID.randomUUID().toString().replace("-",""));
            return message;
        });

        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);


        return Result.success(code);
    }

    @Override
    public Result Login(UserRequest userRequest) {
        if(StringUtils.isAnyBlank(userRequest.getPhone(),userRequest.getCode())){
            return Result.error("手机号或验证码不能为空");
        }
        User byPhone = authFeginService.findByPhone(userRequest.getPhone());
        if(byPhone==null){
            return Result.error("手机号不存在");
        }
        String code = redisTemplate.opsForValue().get(userRequest.getPhone());
        if(StringUtils.isEmpty(code)){
            return Result.error("验证码无效");
        }
        String userKey = UUID.randomUUID().toString().replaceAll("-", "");
        HashMap<String, Object> map = new HashMap<>();
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey, JSONObject.toJSONString(byPhone));

        JwtResponse jwtResponse = new JwtResponse();
        jwtResponse.setToken(token);
        jwtResponse.setExpireTime("30MIN");

        return Result.success(jwtResponse);


    }

    @Override
    public User userInfo() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String user = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return JSON.parseObject(user,User.class);
    }

    @Override
    public Result regist(UserRequest userRequest) {
        //名称是否合法
        if(!validName(userRequest.getName())){
            return Result.error("用户名不合法");
        }

        Integer regist = authFeginService.regist(userRequest);
        if(regist==0){
            return Result.success("注册失败");
        }
        String code = RandomUtil.randomNumbers(4);

        if(StringUtils.isEmpty(code)){
            return Result.error("验证码无效");
        }

        //一分钟只能点这一次
        Boolean aBoolean = redisTemplate.hasKey(userRequest.getPhone());
        if(aBoolean){
            rabbitTemplate.convertAndSend("sendMsg2",userRequest,message -> {
                message.getMessageProperties().setMessageId(UUID.randomUUID().toString().replace("-",""));
                return message;
            });
        }

        //注册成功发送短信
        rabbitTemplate.convertAndSend("sendMsg2",userRequest,message -> {
            message.getMessageProperties().setMessageId(UUID.randomUUID().toString().replace("-",""));
            return message;
        });
        redisTemplate.opsForValue().set(userRequest.getPhone(),code,1, TimeUnit.MINUTES);

        return Result.success("注册成功");

    }

    private boolean validPhone(String phone){
        Pattern compile = Pattern.compile("^(?:(?:\\+|00)86)?1(?:(?:3[\\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\\d])|(?:9[189]))\\d{8}$");
        return compile.matcher(phone).matches();

    }


    private boolean validName(String name){

        //用户名称英文字母大小写、数字,长度在6-15位
        Pattern compile = Pattern.compile("^[a-zA-Z]\\w{4,15}$");
        return compile.matcher(name).matches();

    }
}
